package jpavlich.cardsorter.action;

import fr.inria.zvtm.animation.ActionTimingHandler;
import fr.inria.zvtm.animation.Animation;
import fr.inria.zvtm.engine.VirtualSpace;
import fr.inria.zvtm.engine.VirtualSpaceManager;
import fr.inria.zvtm.glyphs.Glyph;
import fr.inria.zvtm.glyphs.IcePDFPageImg;

public class MoveCard extends Action<MoveCard> {

	private double dx;
	private double dy;
	private String cardID;
	private String vsID;

	public MoveCard(String cardID, String vsID, double dx, double dy) {
		super();
		this.cardID = cardID;
		this.vsID = vsID;
		this.dx = dx;
		this.dy = dy;
	}

	@Override
	public void execute() {
		Glyph glyph = (Glyph) getResourceManager().findResource(cardID);
		if (glyph != null) {
			glyph.move(dx, dy);
		}
	}

	@Override
	public void undo() {
		Glyph glyph = (Glyph) getResourceManager().findResource(cardID);
		if (glyph != null) {
			glyph.move(-dx, -dy);
		}
	}

	@Override
	public MoveCard clone() {
		return new MoveCard(cardID, vsID, dx, dy);
	}

	@Override
	public String toString() {
		return "MoveCard [id=" + cardID + ", dx=" + dx + ", dy=" + dy
				+ ", recordable=" + recordable + ", startTime=" + startTime
				+ ", duration=" + duration + "]";
	}

	@Override
	public Animation createAnimation() {
		final Glyph glyph = (Glyph) getResourceManager().findResource(cardID);
		return VirtualSpaceManager.INSTANCE
				.getAnimationManager()
				.getAnimationFactory()
				.createAnimation((int) duration, glyph,
						Animation.Dimension.POSITION,
						new ActionTimingHandler() {
							private double startX = Double.MIN_VALUE;
							private double startY = Double.MIN_VALUE;
							private double endX = Double.MIN_VALUE;
							private double endY = Double.MIN_VALUE;

							@Override
							public void begin(Object subject,
									Animation.Dimension dim) {
								startX = glyph.getLocation().x;
								startY = glyph.getLocation().y;
								endX = glyph.getLocation().x + dx;
								endY = glyph.getLocation().y + dy;
							}

							@Override
							public void timingEvent(float fraction,
									Object subject, Animation.Dimension dim) {
								glyph.moveTo(startX + fraction
										* (endX - startX), startY + fraction
										* (endY - startY));
							}
						});
	}

}
